package com.josework.springhelloworld.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.josework.springhelloworld.dto.PageResult;
import com.josework.springhelloworld.dto.user.UserEditParams;
import com.josework.springhelloworld.dto.user.UserSearchParams;
import com.josework.springhelloworld.dto.user.UserView;
import com.josework.springhelloworld.exception.UserException;
import com.josework.springhelloworld.mapper.UserMapper;
import com.josework.springhelloworld.model.User;
import com.josework.springhelloworld.service.IUserService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import javax.annotation.PostConstruct;
import java.time.LocalDateTime;
import java.util.List;
import java.util.stream.Collectors;

@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements IUserService, InitializingBean {


    //UserService类-->无参构造方法-->对象-->依赖注入-->初始化前（@PostConstruct）-->初始化后-->放入单例池Map-->Bean
//    @PostConstruct
//    public void a(){
//        System.out.println("hello,a()!");
//    }


    @Override
    public void saveOrUpdate(UserEditParams params) {
        if (params.getId()!=null && params.getId() != 0L){
            User user = this.getById(params.getId());
            if (user != null){
                user = params.copyPropertiesToUser(user);
                user.setUpdateTime(LocalDateTime.now());
                this.updateById(user);
            }
        }else {
            //新增User
            User user = params.copyPropertiesToUser(null);
            user.setAddTime(LocalDateTime.now());
            this.save(user);
        }


    }

    @Override
    public UserView getUserById(Long id) {
        User user = this.getById(id);
        if (user!=null){
            UserView userView = new UserView();
            BeanUtils.copyProperties(user,userView);
            return userView;
        }

        throw new UserException(404,"用户不存在");


    }

    @Override
    public PageResult<UserView> findPage(UserSearchParams params) {

        Page<User> page = new Page<>(params.getPageInfo().pageIndex, params.getPageInfo().pageSize);
        LambdaQueryWrapper<User> wrapper = new LambdaQueryWrapper<>();

        this.addOrder(params.getPageInfo().orderBy, wrapper);
        IPage<User> result = this.page(page, wrapper);

        List<UserView> list = null;
        if (result != null && !CollectionUtils.isEmpty(result.getRecords())) {
            list = result.getRecords().stream().map(
                    e -> {
                        UserView userView = new UserView();
                        BeanUtils.copyProperties(e, userView);
                        return userView;
                    }
            ).collect(Collectors.toList());

        }
        return new PageResult<>(list, result.getTotal(), params.getPageInfo(), null);
    }

    //排序
    private void addOrder(String order, LambdaQueryWrapper<User> wrapper) {
        if (StringUtils.isEmpty(order)) {
            wrapper.orderByDesc(User::getAddTime);
        } else {
            String[] arr = order.trim().split(" ");
            if ("asc".equals(arr[arr.length-1])) {
                wrapper.orderByAsc(User::getAddTime);
            } else {
                wrapper.orderByDesc(User::getAddTime);
            }
        }
    }


    @Override
    public void afterPropertiesSet() throws Exception {
        log.debug("Hello,afterPropertiesSet()");

    }
}
